package com.ys.controller.api.tools;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.service.tools.ToolsCheckRepeatService;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/toolsCheckRepeat")
public class ApiInterToolsCheckRepeatController {
	
	@Autowired
	private ToolsCheckRepeatService toolsCheckRepeatService;

	/*
	 * 上传表格
	 */
	@RequiresPermissions("checkRepeat:view")
	@PostMapping("/readExcel")
	@ResponseBody
	public R readExcel(Model model, HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file) {

		R retMsg = null;

		try {
			List<List<String>> rows = toolsCheckRepeatService.readExcel(file);
			return R.ok(rows);
		} catch (Exception e) {
			e.printStackTrace();
			retMsg = R.error("服务器正在开小差，请联系客服");
		}
		return retMsg;
	}
	
	/**
	 * 查重
	 */
	@PostMapping("/checkRepeat")
    @ResponseBody
	public R checkRepeat(HttpServletRequest request,
			String country, String detailArr){
		
		JSONArray detailJA = JSON.parseArray(detailArr);
		
		StringBuffer sb = new StringBuffer(" ");
		List<List<String>> rows = new ArrayList<List<String>>();
		for (int i = 0; i < detailJA.size(); i++) {
			
			List<String> row = new ArrayList<String>();
			JSONArray rowJA = detailJA.getJSONArray(i);
			for (int j = 0; j < rowJA.size(); j++) {
				String str = rowJA.getString(j);
				if (str != null && str.length() > 0) {
					row.add(rowJA.getString(j));
					sb.append(str + " ");
				}
			}
			rows.add(row);
		}
		
		String text = sb.toString();

		return toolsCheckRepeatService.checkRepeat(country, rows, text);
	}
	
}
